<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

/**
 * Class User
 * @package App
 */
class User extends Model
{

    public $timestamps = false;
    protected $table = 't_member';

    const SEX_OFF = 0;
    const SEX_MAN = 1;
    const SEX_WOMEN = 2;
    static $SexDisplay = [
        self::SEX_OFF => '未知',
        self::SEX_MAN => '男',
        self::SEX_WOMEN => '女',
    ];


    /**
     * 用户信息
     * @param $userinfo
     * @param $key
     * @return array
     */
    static function UserCheck($userinfo, $key)
    {
        //查找是否有该用户信息
        $user = User::select('c_id', 'wx_open_id')->where('union_id', $userinfo['unionid'])->first();
        if (!$user) {
            //该微信没有注册，则注册
            $user = new User();
            $user->name = $userinfo['nickname'];
            $user->c_avatar = $userinfo['headimgurl'] ? $userinfo['headimgurl'] : "http://thirdqq.qlogo.cn/qqapp/1106906206/10B9A25EFCA5F79FD6312960D6019220/100";
            $user->sex = self::$SexDisplay[$userinfo['sex']];
            $user->union_id = $userinfo['unionid'];
            $user->wx_open_id = $userinfo['openid'];
            $user->uuid = self::CreateUuid();
            if (!$user->save()) {
                return ['status' => 2, 'return' => $key];
            }
        }
        //如果没有wx_open_id
        if ($user->wx_open_id !== $userinfo['openid']) {
            if (!User::where('c_id', $user->c_id)->update([
                'wx_open_id' => $userinfo['openid']
            ])) {
                return ['status' => 2, 'return' => $key];
            }
        }
        //返会用户信息
        $token = hashid_encode($user->c_id);
        return ['status' => 1, 'return' => $token, 'c_id' => $user->c_id];
    }


    /**
     * 用户信息
     * @param $hash_id
     * @return array
     */
    static function UserInfo($hash_id)
    {
        $c_id = hashid_decode($hash_id);
        $user = User::select('name', 'c_avatar', 'sex', 'phone')->where('c_id', $c_id)->first();
        if (!$user) {
            return error();
        }
        $userinfo = [
            'user_name' => $user->name,
            'user_avatar' => $user->c_avatar,
            'user_sex' => $user->sex,
            'user_phone' => $user->phone,
            'city' => self::GetCity(),
        ];
        return success(compact('userinfo'));
    }


    /**
     * 用户所在城市
     * @return string
     */
    static function GetCity()
    {

        if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")) {
            $ip = getenv("HTTP_CLIENT_IP");
        } else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")) {
            $ip = getenv("HTTP_X_FORWARDED_FOR");
        } else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")) {
            $ip = getenv("REMOTE_ADDR");
        } else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")) {
            $ip = $_SERVER['REMOTE_ADDR'];
        } else {
            $ip = "unknown";
        }
        if ($ip === "unknown") {
            return "unknown";
        }
        $url = 'http://ip.taobao.com/service/getIpInfo.php?ip=' . $ip;
        $return = Wechat::Curl($url);
        if ($return === FALSE || $return['code'] !== 0) {
            return "地址不正确";
        }
        return $return['data']['city'];
    }


    /**
     * 生成uuid
     * @return string
     */
    static function CreateUuid()
    {
        $str = md5(uniqid(mt_rand(), true));
        $uuid = substr($str, 0, 8) . '-';
        $uuid .= substr($str, 8, 4) . '-';
        $uuid .= substr($str, 12, 4) . '-';
        $uuid .= substr($str, 16, 4) . '-';
        $uuid .= substr($str, 20, 12);
        return $uuid;

    }


    /**
     * @param $uuid
     * @return mixed
     */
    static function CheckUserUuid($uuid)
    {
        return User::where('uuid', $uuid)->value('c_id');
    }


    /**
     * @param $code
     * @return array
     */
    static function GetUserId($code)
    {
        $userinfo = Wechat::GetUserInfo($code);
        //查找是否有该用户信息
        $user = User::select('c_id', 'wx_open_id', 'uuid')->where('union_id', $userinfo['unionid'])->first();
        if (!$user) {
            //该微信没有注册，则注册
            $user = new User();
            $user->name = $userinfo['nickname'];
            $user->c_avatar = $userinfo['headimgurl'] ? $userinfo['headimgurl'] : "http://thirdqq.qlogo.cn/qqapp/1106906206/10B9A25EFCA5F79FD6312960D6019220/100";
            $user->sex = self::$SexDisplay[$userinfo['sex']];
            $user->union_id = $userinfo['unionid'];
            $user->wx_open_id = $userinfo['openid'];
            $user->uuid = self::CreateUuid();
            if (!$user->save()) {
                return error('注册失败');
            }
        }
        //如果没有wx_open_id
        if ($user->wx_open_id !== $userinfo['openid']) {
            if (!User::where('c_id', $user->c_id)->update([
                'wx_open_id' => $userinfo['openid']
            ])) {
                return error('注册失败');
            }
        }
        //返会用户信息
        $user_id = $user->uuid;
        return success(compact('user_id'));
    }
}
